<template>
	<view>
		<view class="navbar">
			<u-navbar :safeAreaInsetTop="true" leftIcon="" bgColor="transparent" :placeholder="true">

				<view class="navbar-left" slot="left" @click="releaseCancel">
					取消
				</view>

				<view class="navbar-center" slot="center">
					发布动态
				</view>

				<view class="navbar-right flex-no-horizontal" :class="{'navbar-right-active':text !== ''}" slot="right"
					@click="releaseClick">
					发布
				</view>

			</u-navbar>
		</view>

		<view class="main box-pading">

			<view class="main-text flex-no-horizontal">

				<textarea v-model="text" maxlength="800" placeholder="请输入内容 (必填)" placeholder-class="main-text-textarea" @input="test" />

			</view>

			<view class="main-img flex-no-horizontal">

				<view class="main-img-item" v-for="(item,index) in imgList" :key="index">
					<image src="../../static/icon/icon-close.png" mode="aspectFill" class="main-img-item-close"
						@click="deleteImg(index)">
					</image>
					<image :src="item.path" class="main-img-item-photo" @click="previewImg" mode="aspectFill"></image>
				</view>

				<view class="main-upload-img flex-no-horizontal" @click="uploadImg" v-if="imgList.length < 9">
					<view class="main-upload-img-content">
						<view>
							<u-icon name="plus" color="#000" size="28"></u-icon>
						</view>
						<view style="margin-top: 20rpx;">添加图片</view>
					</view>
				</view>

			</view>

			<view class="main-plate">

				<view class="main-plate-title">
					选择板块
				</view>

				<view class="main-plate-body flex-no-horizontal">

					<view class="main-plate-item" v-for="(item,index) in sectionList" :key="index"
						@click="sectionClick(item.id)" :class="{'main-plate-item-active':item.id === sectionId}">
						{{item.plate}}
					</view>

				</view>

			</view>
			<view class="f-xs text-center m-t-30" style="opacity: 0.5;">动态需经过审核，违规内容无法显示在社区，请知悉！</view>
		</view>

		<!-- 弹窗-是否保留编辑 -->
		<u-popup :show="popupShow" mode="center" :round="10" @close="popupClose" @open="popupOpen">

			<view class="popup-box">

				<view class="popup-title">
					保留此次编辑？
				</view>

				<view class="popup-bottom flex-no-horizontal">

					<view class="popup-bottom-left flex-no-horizontal" @click="notReserved">
						不保留
					</view>

					<view class="popup-bottom-right flex-no-horizontal" @click="reserved">
						保留
					</view>

				</view>

			</view>

		</u-popup>
	</view>
</template>

<script>
	import {
		communityAddApi,
		communityPlateListApi
	} from '../../api/index.js'
	import {changeDynamicApi} from '../../api/examine.js'
	import {getQiniuData,uploadQiniu} from '../../utility/upload.js'
	export default {
		data() {
			return {
				text: '', //文本
				imgList: [], //图片临时路径
				popupShow: false, //弹出层
				sectionList: [{ //版块数据
					id: 0,
					plate: ''
				}],
				sectionId: '', //板块index
				ifReEdit:false,
				changeDate:null,
			};
		},
		computed: {

		},
		onLoad(e) {
			//获取本地缓存
			this.getLocal()
			//获取版块信息
			this.getPlate()
			if(e.data){
				this.ifReEdit = true
				let detail = JSON.parse(e.data)
				this.changeDate = detail
				this.text = detail.text
				this.imgList = detail.fileName ? detail.fileName.split(',') : [],
				this.imgList.forEach((item,index)=>{
					this.imgList[index] = {
						path:item
					}
				})
			}
		},
		methods: {
			
			test(){
				console.log(this.text)
			},
			
			//获取版块信息
			async getPlate() {
				try {
					const res = await communityPlateListApi({
						pageNum: 1,
						pageSize: 10
					})
					this.sectionList = res.data
				} catch (e) {
					//TODO handle the exception
					uni.showToast({
						title: '获取版块数据失败~',
						icon: 'none'
					})
				}
			},

			//相册或相机选择图片
			uploadImg() {
				uni.chooseImage({
					count: 9 - this.imgList.length,
					success: (res) => {
						console.log(res)
						if ((this.imgList.length + res.tempFiles.length) > 9) {
							this.imgList = res.tempFiles
						} else {
							this.imgList = this.imgList.concat(res.tempFiles)
						}
					}
				})
			},

			//预览图片
			previewImg() {

				let list = this.imgList.map((item, index) => {
					return item.path
				})
				uni.previewImage({
					urls: list,
					success: (res) => {
						console.log(res)
					}
				})
			},

			//删除图片
			deleteImg(index) {
				console.log(index)
				this.imgList.splice(index, 1)
				console.log(this.imgList)
			},

			//弹窗关闭
			popupClose() {

			},

			//弹窗打开
			popupOpen() {

			},

			//弹窗-保留点击
			async reserved() {
				try {

					if (this.text !== '' || this.imgList.length !== 0) {
						//循环保存
						let saveImgList = []
						for (let i = 0; i < this.imgList.length; i++) {
							saveImgList.push(await this.saveImgToLocal(this.imgList[i].path))
						}

						let local = {
							text: this.text,
							imgList: saveImgList.toString(),
							plate: this.sectionId
						}
						uni.setStorageSync('releaseData', JSON.stringify(local))
					}

				} catch (e) {
					uni.showToast({
						title: e.message || e.data,
						icon: 'none'
					})
				}
				this.popupShow = !this.popupShow
				uni.navigateBack()
			},

			//弹窗-不保留点击
			notReserved() {
				this.popupShow = !this.popupShow
				uni.navigateBack()
			},

			//版块选择点击
			sectionClick(index) {
				this.sectionId = index
			},

			//发布点击
			async releaseClick() {
				try {

					if (this.sectionId === '') {
						uni.showToast({
							title: '请选择版块',
							icon: 'none'
						})
						return
					}

					if (this.text === '') {
						uni.showToast({
							title: '请输入内容',
							icon: 'none'
						})
						return
					}
					
					if(this.ifReEdit){
						if(this.text === this.changeDate.text){
							uni.showToast({
								title: '请修改内容',
								icon: 'none'
							})
							return
						}
					}

					uni.showLoading({
						mask: true,
						title: '请稍后'
					})

					if (this.imgList !== '') {

						//获取上传地址
						const res = await getQiniuData()
						
						//循环上传
						let serviceImgList = []
						if(!this.ifReEdit){
							for (let i = 0; i < this.imgList.length; i++) {
								// await this.ifCodeImg(this.imgList[i].path)
								const url = await uploadQiniu(res.data, this.imgList[i])
								serviceImgList.push(res.data.domain + url.key)
							}
						}else{
							serviceImgList = this.imgList.toString()
							const changeRes = await changeDynamicApi({id:this.changeDate.dynamicId})
						}
						
						// 新增文章
						const addRes = await communityAddApi({
							plate: this.sectionId, //板块
							text: this.text, //文本
							fileName: serviceImgList.toString(), //文件
						})

						uni.showToast({
							title: '操作成功',
							icon: 'none'
						})

						//判断是否有缓存
						if (uni.getStorageSync('releaseData')) {
							//删除本地图片
							this.getLocalImg()
							//删除本地缓存
							uni.removeStorageSync('releaseData');
						}
					} else {
						if(this.ifReEdit){
							const changeRes = await changeDynamicApi({id:this.changeDate.dynamicId})
						}
						//新增文章
						const addRes = await communityAddApi({
							plate: this.sectionId, //板块
							text: this.text, //文本
							fileName: '', //文件
						})
						
					}
					uni.$emit('detailBlack')
					uni.hideLoading()
					uni.navigateBack()
				} catch (e) {
					uni.hideLoading()
					uni.showToast({
						title: e.message || e.data,
						icon: 'none'
					})
				}
			},

			//发布取消
			releaseCancel() {
				if (this.text || this.imgList.length || this.sectionId) {
					this.popupShow = true
				} else {
					uni.navigateBack()
				}
				//判断是否有缓存
				if (uni.getStorageSync('releaseData')) {
					//删除本地图片
					this.getLocalImg()
					//删除本地缓存
					uni.removeStorageSync('releaseData');
				}
			},

			//保存图片到本地
			saveImgToLocal(url) {
				return new Promise((resolve, reject) => {
					uni.saveFile({
						tempFilePath: url,
						success: (res) => {
							resolve(res.savedFilePath)
						},
						fail: (err) => {
							reject(err.errMsg)
						}
					})
				})
			},

			//删除本地图片
			deleteImgToLocal(url) {
				return new Promise((resolve, reject) => {
					uni.removeSavedFile({
						filePath: url,
						success: (res) => {
							resolve(res)
						},
						fail: (err) => {
							reject(err)
						}
					})
				})
			},

			//获取本地图片路径，并删除
			async getLocalImg() {
				let saveImgList = []
				uni.getSavedFileList({
					success: (saveImgRes) => {
						saveImgList = saveImgRes
					}
				});

				for (let i = 0; i < saveImgList.length; i++) {
					await this.deleteImgToLocal(saveImgRes[i].filePath)
				}

			},

			//获取本地缓存
			getLocal() {
				try {
					const value = uni.getStorageSync('releaseData');
					if (value) {
						let data = JSON.parse(value)
						this.text = data.text
						this.imgList = data.imgList ? data.imgList.split(',') : []
						this.sectionId = data.plate ? parseInt(data.plate) : ''
						this.imgList.forEach((item, index) => {
							this.imgList[index] = {
								path: item
							}
						})
					}
				} catch (e) {
					// error
				}
			},

			//查看上传的图片是否有二维码图片
			// ifCodeImg(url) {
			// 	return new Promise((resolve, reject) => {
			// 		plus.barcode.scan(url, (type, res) => {
			// 			reject({
			// 				message: '上传的图片中有违规图片（如，一维码，二维码图片）'
			// 			})
			// 			console.log(res)
			// 		}, (e) => {
			// 			resolve(true)
			// 		})
			// 	})
			// },

		},
	};
</script>

<style lang="scss">
	.navbar {

		.navbar-left {
			color: $uni-color-black;
			font-size: $uni-font-size-lg;
		}

		.navbar-center {
			color: $uni-color-black;
			font-size: $uni-font-size-lg;
			font-weight: bold;
		}

		.navbar-right {
			justify-content: center;
			width: 145rpx;
			height: 60rpx;
			background-color: rgba(247, 247, 247, 1);
			border-radius: 30rpx;
			color: rgba(167, 167, 167, 1);
			font-size: $uni-font-size-base;
		}

		.navbar-right-active {
			background-color: rgba(74, 188, 90, 1);
			color: #FFFFFF;
		}

	}

	.main {

		.main-text {
			height: 300rpx;
			width: 100%;
			margin: 50rpx 0;
			justify-content: center;

			textarea {
				width: 100%;
				height: 100%;
				font-size: $uni-font-size-base;
			}

			.main-text-textarea {
				font-size: $uni-font-size-base;
				color: rgba(167, 167, 167, 1);
			}

		}

		.main-img {

			width: 100%;
			flex-wrap: wrap;
			margin-bottom: 50rpx;

			.main-upload-img {
				height: 216rpx;
				width: 31.5%;
				margin-right: 11rpx;
				border-radius: 14rpx;
				background-color: rgba(247, 247, 247, 1);
				justify-content: center;

				.main-upload-img-content {

					view {
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: $uni-font-size-sm;
						color: $uni-color-black;
					}

				}

			}

			.main-img-item {
				width: 32%;
				height: 216rpx;
				margin-right: 1.33%;
				position: relative;
				margin-bottom: 10rpx;

				.main-img-item-close {
					width: 30rpx;
					height: 30rpx;
					position: absolute;
					right: 10rpx;
					top: 10rpx;
					z-index: 2;
				}

				.main-img-item-photo {
					width: 100%;
					height: 216rpx;
					border-radius: 14rpx;
				}
			}
		}

		.main-plate {

			.main-plate-title {
				font-size: $uni-font-size-base;
				color: $uni-color-black;
				margin-bottom: 30rpx;
			}

			.main-plate-body {
				flex-wrap: wrap;

				.main-plate-item {
					margin-bottom: 20rpx;
					border-radius: 27rpx;
					font-size: 22rpx;
					color: $uni-color-black;
					padding: 15rpx 30rpx;
					background-color: rgba(247, 247, 247, 1);
					margin-right: 20rpx;
				}

				.main-plate-item-active {
					background-color: rgba(74, 188, 90, 1);
					color: #FFFFFF;
				}

			}

		}

	}

	.popup-box {
		padding: 68rpx 40rpx 60rpx 40rpx;
		background-color: #FFFFFF;
		border-radius: 20rpx;

		.popup-title {
			text-align: center;
			color: $uni-color-black;
			font-size: $uni-font-size-lg;
			margin-bottom: 60rpx;
		}

		.popup-bottom {
			justify-content: space-between;

			.popup-bottom-left {
				justify-content: center;
				width: 235rpx;
				height: 80rpx;
				border-radius: 40rpx;
				background-color: rgba(247, 247, 247, 1);
				color: rgba(178, 180, 181, 1);
				font-size: $uni-font-size-base;
				margin-right: 40rpx;
			}

			.popup-bottom-right {
				justify-content: center;
				width: 235rpx;
				height: 80rpx;
				border-radius: 40rpx;
				background-color: rgba(55, 214, 123, 1);
				color: #FFFFFF;
				font-size: $uni-font-size-base;
			}

		}

	}
</style>
